#include "LapItem.hpp"
#include "Clock.hpp"
#include "AssetManager.hpp"
#include "Notification.hpp"
#include "Util.hpp"
#include <cpp3ds/System/I18n.hpp>
#include <cpp3ds/System/FileSystem.hpp>
#include <TweenEngine/Tween.h>
#include <time.h>
#include <stdlib.h>

namespace Clock {

LapItem::LapItem(int lapCount, cpp3ds::Time fullTime, cpp3ds::Time oldTime)
: m_height(16.f)
, m_index(0)
{
	m_textLap.setCharacterSize(10);
	m_textLap.setFillColor(cpp3ds::Color(99, 99, 99));
	m_textLap.setPosition(2.f, 2.f);
	m_textLap.setString(_("%i", lapCount));

	m_textTime = m_textLap;
	m_textTime.setFillColor(cpp3ds::Color(33, 33, 33));

	m_textTimeDiff = m_textLap;
	m_textTimeDiff.setPosition(145.f, 2.f);

	int seconds = (int)fullTime.asSeconds() % 60;
	int minutes = (int)fullTime.asSeconds() / 60;
	int hours = minutes / 60;

	if (hours > 0) {
		m_textTime.setString(_("%i:%02d:%02d.%03d", hours, minutes % 60, seconds, fullTime.asMilliseconds() % 1000));
	} else if (minutes > 0) {
		m_textTime.setString(_("%i:%02d.%03d", minutes, seconds, fullTime.asMilliseconds() % 1000));
	} else {
		m_textTime.setString(_(":%02d.%03d", seconds, fullTime.asMilliseconds() % 1000));
	}
	m_textTime.setPosition(m_textLap.getPosition().x + m_textLap.getLocalBounds().width + 5.f, 2.f);

	if (oldTime > cpp3ds::Time::Zero && oldTime <= fullTime) {
		cpp3ds::Time diffTime = fullTime - oldTime;

		seconds = (int)diffTime.asSeconds() % 60;
		minutes = (int)diffTime.asSeconds() / 60;
		hours = minutes / 60;
		if (hours > 0) {
			m_textTimeDiff.setString(_("%i:%02d:%02d.%03d", hours, minutes % 60, seconds, diffTime.asMilliseconds() % 1000));
		} else if (minutes > 0) {
			m_textTimeDiff.setString(_("%i:%02d.%03d", minutes, seconds, diffTime.asMilliseconds() % 1000));
		} else {
			m_textTimeDiff.setString(_(":%02d.%03d", seconds, diffTime.asMilliseconds() % 1000));
		}
	} else {
		m_textTimeDiff.setString("--:--");
	}
	m_textTimeDiff.setOrigin(m_textTimeDiff.getLocalBounds().width, 0.f);

	m_itemBackground.setPosition(0.f, 0.f);
	m_itemBackground.setFillColor(cpp3ds::Color(245, 245, 245));
	m_itemBackground.setOutlineColor(cpp3ds::Color(158, 158, 158));
	m_itemBackground.setOutlineThickness(1);
	m_itemBackground.setSize(cpp3ds::Vector2f(150.f, 16.f));

	m_index = lapCount;
	m_time = fullTime;
}

LapItem::~LapItem()
{

}

void LapItem::draw(cpp3ds::RenderTarget &target, cpp3ds::RenderStates states) const
{
	states.transform *= getTransform();

	target.draw(m_itemBackground, states);
	target.draw(m_textLap, states);
	target.draw(m_textTime, states);
	target.draw(m_textTimeDiff, states);
}

void LapItem::update(float delta)
{
	m_tweenManager.update(delta);
}

void LapItem::processEvent(const cpp3ds::Event& event)
{

}

float LapItem::getHeight() const
{
	return m_height;
}

int LapItem::getIndex()
{
	return m_index;
}

cpp3ds::Time LapItem::getTime()
{
	return m_time;
}

} // namespace Clock
